#!/usr/bin/python3
# -*- coding=utf-8 -*-

from random_string import RandomString

import os
import yaml

CONFIG_FILE = 'gen_code.yaml'

def get_config(file_name):
    """
    解析yaml
    :file_name: 配置文件名
    :returns: setting dict

    """

    if not os.path.exists(file_name):
        return {}

    with open(file_name, "r") as f:
        # return yaml.load(f, Loader=yaml.FullLoader) #高版本
        return yaml.load(f)

def main():
    config = get_config(os.path.join(os.path.dirname(__file__), CONFIG_FILE))
    setting = config.get('setting', {})
    db = setting.get('db', {})
    file_info = setting.get('file', {})
    args = setting.get('args', {})

    codes = set()
    n = args.get('number')
    char1 = args.get('char1')
    char2 = args.get('char2')
    rs = RandomString(args.get('length'))
    while len(codes) < n:
        code = rs.get_id()
        new_code = code[0:2] + char1 + code[2:6] + char2 + code[6:]
        codes.add(new_code)
    sql_f = open(file_info.get('sql_file'), 'wb')
    copy_f = open(file_info.get('copy_file'), 'wb')
    sql_f.write("insert into `{0}` (`{1}`, `{2}`) values\n".format(db.get('table'), db.get('column_id'), db.get('column_type')))
    first = True
    for str in codes:
        if first:
            first = False
        else:
            sql_f.write(',\n')

        sql_f.write("('{0}', {1})".format(str, args.get('type')))
        copy_f.write(str + '\n')

    sql_f.write(';\n')
    sql_f.close()
    copy_f.close()

if __name__ == '__main__':
    main()
